var express = require('express');
var session = require('express-session');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('log4js');
var log = logger.getLogger('app.js');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var compression = require('compression');
var config = require('./config');

	
var app = express();
app.use(compression());
app.use(express.static(path.join(__dirname, '/public'), {maxAge: '3d'}));

// view engine setup
app.set('views', __dirname + '/src');
app.engine('.html', require('ejs').__express);
app.set('view engine', 'html');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/images/icon.jpg'));

app.use(logger.connectLogger(logger.getLogger('http'), {level: logger.levels.INFO}));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

//app.use(bodyParser.urlencoded({extended: true, limit: '50mb'}));
app.use(bodyParser.raw({extended: true, limit: '50mb'}));
app.use(bodyParser.raw({extended: true, limit: '50mb', type: 'image/jpeg'}));
app.use(bodyParser.raw({extended: true, limit: '50mb', type: 'image/*'}));

app.use(cookieParser());


app.enable('trust proxy');
require('./router')(app);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        if(err && err.status != 404) log.error(err);
        res.render('system/views/404', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    if(err && err.status != 404) log.error(err);
    res.render('system/views/404', {
        message: err.message,
        error: {}
    });
});


module.exports = app;